<template>
  <div class="app-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :style="{'height': formHeight}" class="edit-form">
        <el-row>
          <el-col :span="22" v-if="storeEnable">
            <el-form-item label="商店" prop="storeId">
              <el-select
                ref="storeId"
                v-model="form.storeId"
                filterable
                remote
                reserve-keyword
                default-first-option
                style="width: 100%"
                placeholder="请选择商店"
                :remote-method="getStoreList"
                :loading="storeLoading">
                <el-option
                  v-for="item in storeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="商品名称" prop="name">
              <el-input ref="name" v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="商品类别" prop="categoryId">
              <treeselect ref="categoryId" v-model="form.categoryId" :options="categoryEditOptions" :normalizer="normalizer" placeholder="请选择商品类别" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-col :span="11">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status" disabled>
                  <el-radio
                    v-for="dict in dict.type.shop_goods_status"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="3">
                <el-form-item label="上下架时间" prop="onOffTime">
                  <el-tag>{{form.onOffTime}}</el-tag>
<!--                  <el-date-picker disabled-->
<!--                                  v-model="form.onOffTime"-->
<!--                                  type="date"-->
<!--                                  value-format="yyyy-MM-dd"-->
<!--                                  placeholder="请选择上下架时间">-->
<!--                  </el-date-picker>-->
                </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="22">
            <el-form-item label="商品缩略图" prop="imgAbbrev">
              <image-upload ref="imgAbbrev" v-model="form.imgAbbrev" :biz-id="goodsId" biz-code="SHOP_GOODS_ABBREV" :limit="1" @input="imgAbbrevChange"></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="商品轮播图" prop="imgDetails">
              <image-upload ref="imgDetails" v-model="form.imgDetails" :biz-id="goodsId" biz-code="SHOP_GOODS_DETAIL" zoom="0"></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="商品描述" prop="goodsDesc">
              <editor v-model="form.goodsDesc" :min-height="192"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="推荐指数" prop="recValue" v-hasPermi="['shop:goods:rec']">
              <el-input v-model="form.recValue" placeholder="请输入推荐指数" maxlength="4"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="实际价格（元）" prop="price">
              <el-input-number v-model="form.price" placeholder="请输入商品实际价格" controls-position="right" :min="0" :step="1" :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="查看次数" prop="viewNum">
              <el-input-number v-model="form.viewNum" placeholder="请输入查看次数" disabled controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="成本（元）" prop="cost">
              <el-input-number v-model="form.cost" placeholder="请输入商品成本" controls-position="right" :min="0" :step="1" :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="销量" prop="saleNum">
              <el-input-number v-model="form.saleNum" placeholder="请输入销量" controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="原价格（元）" prop="priceSrc">
              <el-input-number v-model="form.priceSrc" placeholder="请输入商品原价格" controls-position="right" :min="0" :step="1" :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="总库存" prop="stockTotal">
              <el-input-number v-model="form.stockTotal" placeholder="请输入总库存" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
  </div>
</template>

<script>
import { getGoods, addGoods, updateGoods, onOffGoods } from "@/api/shop/goods";
import { listCategory, handleCascader } from "@/api/shop/category";
import { listStore, getStore } from "@/api/shop/store";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "GoodsAdd",
  dicts: ['shop_goods_status'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 表单的高度
      formHeight: document.documentElement.scrollHeight - 160 + "px",
      // 遮罩层
      loading: true,
      // 表单参数
      form: {},
      storeId: null,
      goodsId: null,
      // 表单校验
      rules: {
        storeId: [
          { required: true, trigger: "blur", message: "请选择商店" }
        ],
        categoryId: [
          { required: true, trigger: "blur", message: "请选择商品类别" }
        ],
        name: [
          { required: true, trigger: "blur", message: "请输入商品名称" }
        ],
        imgAbbrev: [
          { required: true, trigger: "blur", message: "请上传缩略图" }
        ],
        imgDetails: [
          { required: true, trigger: "blur", message: "请上传轮播图" }
        ],
      },
      // 编辑时商品类别选择框
      categoryEditOptions: [],
      // 商店数据源
      storeOptions: [],
      // 商店选择遮罩
      storeLoading: false
    };
  },
  created() {
    const goodsId = this.$route.query && this.$route.query.goodsId;
    const storeId = this.$route.query && this.$route.query.storeId;
    if (goodsId) {
      this.goodsId = Number(goodsId)
      this.getGoods(goodsId);
    } else {
      this.getStoreList();
    }
    if (storeId) {
      this.storeId = storeId;
    }
    this.reset();
    this.getTreeselect();
  },
  computed: {
    // 是否禁用
    storeEnable() {
      return !this.storeId;
    },
  },
  methods: {
    /** 转换文创商品类别数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询文创商品类别下拉树结构 */
    getTreeselect() {
      listCategory().then(response => {
        this.categoryOptions = [];
        const editData = { id: 0, name: '顶级节点', children: [] };
        editData.children = this.handleTree(response.data, "id", "parentId");
        this.categoryEditOptions.push(editData);
        this.categoryOptions = handleCascader(response.data);
      });
    },
    /** 查询文创商店列表 */
    getStoreList(query) {
      if (query !== '') {
        this.storeLoading = true;
        const queryParams = {
          name: query
        }
        listStore(queryParams).then(response => {
          this.storeOptions = response.rows;
          this.storeLoading = false;
        });
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeId: this.storeId,
        categoryId: null,
        name: null,
        imgAbbrev: null,
        imgDetails: null,
        goodsDesc: null,
        cost: 0,
        priceSrc: 0,
        price: 0,
        recValue: null,
        viewNum: null,
        saleNum: null,
        status: "1",
        onOffTime: null,
        stockTotal: 0
      };
      this.resetForm("form");
    },
    /** 查询商品信息 */
    getGoods(id) {
      this.reset();
      this.storeOptions = []
      getGoods(id).then(response => {
        this.form = response.data;
        this.form.price /= 100;
        this.form.priceSrc /= 100;
        this.form.cost /= 100;
        getStore(response.data.storeId).then(response => {
          this.storeOptions.push(response.data);
        })
      });
    },
    /** 设置商品规格按钮操作 */
    handleSpec(row) {
      const id = row.id;
      const name = row.name;
      this.$tab.openPage("[" + name + "]配置规格", '/shop/goods-spec-edit/index/' + id);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid, object) => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.form.id = response.data.id;
              this.goodsId = response.data.id;
              // this.form.price /= 100;
              // this.form.priceSrc /= 100;
              // this.form.cost /= 100;
            });
          }
        } else {
          let str = []
          for (let key in object) {
            object[key].map(item => {
              str.push(item.message)
            })
            let dom = this.$refs[Object.keys(object)[0]]
            if (Object.prototype.toString.call(dom) !== '[object Object]') {
              dom = dom[0]
              break
            }
            // 定位代码
            dom.$el.scrollIntoView({
              block: 'center',
              behavior: 'smooth'
            });
          }
          this.$modal.msgError(str.join(', '));
        }
      });
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: "/shop/goods/goods", query: {goodsId: this.goodsId} };
      this.$tab.closeOpenPage(obj);
    },
    /** 提取url到form，用于保存 */
    imgAbbrevChange(val) {
      if (val && val.length) {
        this.form.imgAbbrev = val[0].zoomUrl;
      }
    }
  },
  watch: {}
};
</script>
<style lang="scss">
.edit-form {
  overflow-y: auto;
}
</style>
